package top.italks.safeandroid.extend;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class ExTextView extends androidx.appcompat.widget.AppCompatTextView {
    private  String TAG = this.getClass().getSimpleName();
    private LinearGradient mLinearGradient;
    private Matrix mGradientMatrix;
    private float mTranslate = 0.0f;
    private int mViewWidth = 0;
    private Paint mPaint;
    public ExTextView(Context context) {
        super(context);
    }
    public ExTextView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

//    public ExTextView(
//            @NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
//        super(context, attrs, defStyleAttr);
//    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Log.e(TAG, "onDraw ----- 1");
        if (mLinearGradient != null) {
            mTranslate += mViewWidth / 8;
            if (mTranslate > mViewWidth) {
                mTranslate = 0;
            }

            mGradientMatrix.setTranslate(mTranslate, 0.0f);
            mLinearGradient.setLocalMatrix(mGradientMatrix);
//            postInvalidateDelayed(100);
            Log.e(TAG, "onDraw ----- mTranslate " + mTranslate + " over.");

            postInvalidateDelayed(200);
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        Log.e(TAG, "onSizeChanged ----- 1");
        if (mViewWidth == 0) {
            mViewWidth = getMeasuredWidth();
            Log.e(TAG, "onSizeChanged ----- mViewWidth " + mViewWidth);
            if (mViewWidth > 0) {
                mPaint = getPaint();
                mLinearGradient = new LinearGradient(0, 0, mViewWidth, 0,
                        new int[]{
                                Color.BLUE, 0xFFFFFF,
                                Color.RED
                        },
                        null,
                        Shader.TileMode.CLAMP);
                mPaint.setShader(mLinearGradient);
                mGradientMatrix = new Matrix();
                Log.e(TAG, "onSizeChanged ----- mViewWidth " + mViewWidth + " over.");
            }
        }

    }
}
